package com.jetgege.smartbox.Base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.jetgege.smartbox.AddBox.AddDeviceActivity;
import com.jetgege.smartbox.Tools.BluetoothHelper;

import butterknife.ButterKnife;


/**
 * Created by JJT-ssd on 2017/2/3.
 */

public abstract class BaseActivity extends AppCompatActivity {


    private ForceOfflineReceiver receiver;

    protected abstract int getLayoutId();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        registerBroadcast();
        ActivityCollector.addActivity(this);
    }

    class ForceOfflineReceiver extends BroadcastReceiver
    {
        Context mContext;

        public ForceOfflineReceiver(Context mContext)
        {
            IntentFilter intentFilter=new IntentFilter();
            intentFilter.addAction("com.jetgege.broadcast.logout");
            this.mContext=mContext;
            mContext.registerReceiver(this,intentFilter);
        }

        public  void unregisterReceiver()
        {
            mContext.unregisterReceiver(this);
        }
        @Override
        public void onReceive(final Context context, Intent intent) {
            if (intent.getAction().equals("com.jetgege.broadcast.logout"))
            {
                BluetoothHelper.cancle();
               if (!ActivityCollector.finishAll()){
                   App.editor.putBoolean("isFirstUse",true);
                   App.editor.commit();
                   Intent startIntent=new Intent(context, AddDeviceActivity.class);
                   startIntent.setAction("StartActivity");
                   startActivity(startIntent);
               }
            }
        }
    }

    private void registerBroadcast() {
        receiver=new ForceOfflineReceiver(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
        if (receiver!=null) receiver.unregisterReceiver();
        receiver=null;
    }

}

